<!-- 订单列表 -->
<template>
  <el-scrollbar>
    <div class="search-container">
      <el-input v-model="search" size="small" placeholder="请输入订单号" style="width: 200px;" @input="handleSearch"
        clearable>
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="filterTableData" style="width: 100%" height="700">
      <!-- 展开行显示订单详情 -->
      <el-table-column prop="orderId" label="订单ID" width="120" show-overflow-tooltip />
      <el-table-column prop="orderNumber" label="订单号" width="120" show-overflow-tooltip />
      <el-table-column prop="userId" label="用户ID" width="120" />
      <el-table-column prop="orderType" label="订单类型" width="120">
        <template #default="{ row }">
          <el-tag size="small" :type="row.orderType === '外带' ? 'warning' : 'info'">
            {{ row.orderType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="总价" width="120">
        <template #default="{ row }">
          ¥{{ row.totalPrice }}
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getOrderStatusType(row.orderStatus)">
            {{ row.orderStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="reservation" label="取餐方式" width="120" />
      <el-table-column prop="orderDate" label="下单时间" show-overflow-tooltip>
        <template #default="{ row }">
          {{ formatDate(row.orderDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="pickDate" label="取餐时间" show-overflow-tooltip>
        <template #default="{ row }">
          {{ formatDate(row.pickDate) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="showOrderDetail(row)">
            查看详情
          </el-button>
          <el-button type="danger" size="small" @click="deleteOrder(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- ���加分页组件 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[6, 12, 24, 48]"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next"
      class="pagination"
    />

    <OrderDetail v-model="dialogVisible" :orderDetailList="currentOrderDetails" />
  </el-scrollbar>
</template>

<script setup>
import { onMounted, ref, computed} from "vue";
import axios from "axios";
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import OrderDetail from './OrderDetail.vue'

const orders = ref([]);
const search = ref("");

// 控制对话框显示
const dialogVisible = ref(false)
// 当前订单详情数据
const currentOrderDetails = ref([])

// 添加分页相关的响应式变量
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取订单状态对应的标签类型
const getOrderStatusType = (status) => {
  const typeMap = {
    '未完成': 'warning',
    '已付款': 'info',
    '已发货': 'primary',
    '完成': 'success'
  }
  return typeMap[status] || ''
}

const deleteOrder = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该订单吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
       
      }
    )

    const response = await axios.post('/deleteOrder', 
      row.orderId,  // 直接发送userId值，而不是对象
      {
        headers: {
          'Content-Type': 'application/json',
          Authorization: sessionStorage.getItem('Authorization')
        }
      }
    )
    if (response.data.status === 200) {
      ElMessage.success(response.data.message);
      orders.value = orders.value.filter(order => order.orderId !== row.orderId);
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 过滤订单列表
const filterTableData = computed(() =>
  orders.value.filter(
    (order) =>
      !search.value ||
      order.orderNumber.toLowerCase().includes(search.value.toLowerCase())
  )
)

// 获取订单列表
const fetchOrders = async () => {
  try {
    const response = await axios.get("/orderList", {
      params: {
        current: currentPage.value,
        size: pageSize.value
      },
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      },
    });
    if (response.data.status === 200) {
      orders.value = response.data.data.records;
      total.value = response.data.data.total;
    } else {
      ElMessage.error(response.data.msg || '获取订单列表失败');
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败');
  }
};

// 查看订单详情
const showOrderDetail = async (row) => {
  try {
    const response = await axios.get(`/detail/${row.orderId}`, {
      headers: {
        Authorization: sessionStorage.getItem("Authorization"),
      },
    });
    if (response.data.status === 200) {
      // 合并订单信息和订单详情
      const orderData = response.data.data;
      currentOrderDetails.value = orderData.orderDetails.map(detail => ({
        ...detail,
        orderId: orderData.order.orderId,
        userId: orderData.order.userId,
        orderNumber: orderData.order.orderNumber,
        orderType: orderData.order.orderType,
        totalPrice: orderData.order.totalPrice,
        orderStatus: orderData.order.orderStatus,
        orderDate: orderData.order.orderDate,
        pickDate: orderData.order.pickDate
      }));
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.data.message || '获取订单详情失败');
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败');
  }
}

// 搜索处理函数
const handleSearch = () => {
  console.log('搜索关键词：', search.value);
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchOrders();
}

// 处理每页显示数量改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
  fetchOrders();
}

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.search-container {
  padding: 20px;
  background-color: #fff;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.el-input {
  margin-right: 10px;
}

:deep(.el-table__expanded-cell) {
  padding: 20px !important;
}

:deep(.el-table__expand-icon) {
  margin-right: 10px;
}

:deep(.el-tag) {
  margin-right: 0;
}

/* 添加分页组件的样式 */
.pagination {
  display: flex;
  justify-content: center;  /* 水平居中 */
  align-items: center;      /* 垂直居中 */
}
</style>